<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthRule;
use app\api\model\v1\Users;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class Admin extends BaseController
{
    use SearchDataForModel,FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 9:42
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 后端用户列表
     */
    public function adminList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit');
        $map = [];
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        if ($this->request->has('mobile') && !empty($this->request->param('mobile'))) {
            $map[] = ['mobile', 'like', '%' . $this->request->param('mobile') . '%'];
        }
        $type = $this->request->param('auth', 2);
        if (intval($type) === 1) {
            $admin = Admins::find($this->request->uid);
            if ($admin['enter_unit_id'] !== 0) {
                $map[] = ['id', '=', $this->request->uid];
            }
        }
        $data = Admins::with(['roles', 'unit'])->where($map)->paginate($limit)->each(function ($item, $key) {
            $pinjie = "";
            foreach ($item['roles'] as $k => $v) {
                $pinjie .= $v['title'] . ',';
            }
            $item['role_name'] = rtrim($pinjie, ',');
            return $item;

        });
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 9:43
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新
     */
    public function adminUpdateShow()
    {
        $id = $this->request->param('id');
        $user = Admins::find($id);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data =
                AuthRule::field('id,name')->where('is_open', AuthRule::OPEN_ONE)
                    ->select()
                    ->toArray();
        } else {
            $data = AuthRule::field('id,name')
                ->where('id', 'in', implode(',', $role_ids))
                ->where('is_open', AuthRule::OPEN_ONE)
                ->select()->toArray();
        }
        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        return $this->response($user->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 9:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户新增or编辑
     */
    public function adminSave()
    {

        $id = $this->request->param('id', 0);

        try {
            $validator = $this->validate($this->request->param(),
                \app\api\validate\v1\Admin::rules($id),
                \app\api\validate\v1\Admin::msg());
            if ($validator) {
                $data = $this->request->except(['password_confirm']);
                if (empty($data['enter_unit_id'])) {
                    $data['enter_unit_id'] = 0;
                }
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    Admins::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = Admins::find($id);
                    $user->update($data);
                }

                //添加用户角色中间表信息
                //GroupUserPivot::roleUserSave($user,$this->request->param('role_id'));
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 9:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function adminDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            if (intval($id) === 1) {
                return $this->response(403, '超级管理员,不能删除');
            }
            $user = Admins::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/14
     * @Time: 10:45
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 验证密码
     */
    public function checkPassword()
    {
        $data = $this->request->param();
        $user = Users::find($this->request->wx_user_id);
        if (is_null($user)) {
            return $this->response(404, '此微信用户不存在');
        }
        $admin = Admins::find($user['admin_id']);
        if (is_null($admin)) {
            return $this->response(404, '此后台用户不存在');
        }
        $password = $admin->visible(['password'])->toArray();
        if (!password_verify($data['password'], $password['password'])) {
            return $this->response(404, '原始密码输入不正确');
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/14
     * @Time: 11:12
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 修改手机号和密码
     */
    public function updatePassword(){
        $data = $this->request->param();
        $user = Users::find($this->request->wx_user_id);
        if (is_null($user)) {
            return $this->response(404, '此微信用户不存在');
        }
        $admin = Admins::find($user['admin_id']);
        if (is_null($admin)) {
            return $this->response(404, '此后台用户不存在');
        }
        $checkMobile = Admins::where(['mobile'=>$data['mobile']])->find();
        if(!is_null($checkMobile)){
            if ($checkMobile['id'] !== $admin['id']){
                return $this->response(404, '此手机号已绑定其他用户');
            }
        }
        if ($data['newPassword'] !== $data['confirmPassword']){
            return $this->response(404, '两次密码输入不一致');
        }
        $admin->save([
            'mobile'=>$data['mobile'],
            'password'=>password_hash(!empty($data['newPassword']) ? $data['newPassword'] : '111111',PASSWORD_DEFAULT)
        ]);

        return $this->response();
    }



    public function importAdmin(){
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');

        $result = $this->saveImportExcel($file, 'import_excel', 'stage');
        $is_bool = Admins::saveAdminExcel($result, 1);
        if ($is_bool) {
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }

}
